﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LX.Web.Excel;
using S4Store.Persistent;

namespace S4Store.Service
{
    public class DomainImportHelper<T> : ImportHelper<T>
    {
        public S4StoreDataContext PersistentContext { get; set; }

        public DomainImportHelper()
        {
            PersistentContext = new S4StoreDataContext();
        }

        protected override void TransValue(System.Reflection.PropertyInfo p, ImportItem item)
        {
            if (p.PropertyType != typeof(int)) return;
            var attrs = p.GetCustomAttributes(typeof(ImportAttribute), true);
            if (attrs != null && attrs.Any())
            {
                var attr = (ImportAttribute)attrs[0];
                if (attr.Reference != null)
                {
                    if (item.Value == null || item.Value.ToString() == "")
                    {
                        throw new Exception("第" + item.Row + "行," + item.Name + "是必填项");
                    }
                    int id = 0;

                    var valuestr = item.Value.ToString().Replace("（", "(").Replace("）", ")").Trim();
                   // var reg = new System.Text.RegularExpressions.Regex(@"[\s\t\r\n]");
                    //valuestr = reg.Replace(valuestr, "");

                    System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex("^\\d+$");
                    if (reg1.IsMatch(valuestr))
                    {
                        id = int.Parse(valuestr);
                    }
                    else
                    {
                        System.Text.RegularExpressions.Regex reg2
                            = new System.Text.RegularExpressions.Regex("\\((\\d+)\\)$");
                        if (reg2.IsMatch(valuestr))
                        {
                            var idstr = reg2.Match(valuestr).Groups[1].Captures[0].Value;
                            id = int.Parse(idstr);
                        }
                    }
                    

                    var obj = PersistentContext.Set(attr.Reference).Find(id);
                    if (obj != null)
                    {
                        item.Value = id;
                        return;
                    }

                    if (attr.Reference == typeof(Domain.CarModel))
                    {
                        Domain.CarModel model = GetModel<Domain.CarModel>(() =>
                        {
                            return PersistentContext.Set<Domain.CarModel>().Where(o => o.Name.Trim() == valuestr);
                        }, item);
                        if (model != null)
                        {
                            item.Value = model.Id;
                            return;
                        }
                    }

                    if (attr.Reference == typeof(Domain.Employee))
                    {
                        Domain.Employee model = GetModel<Domain.Employee>(() =>
                        {
                            return PersistentContext.Set<Domain.Employee>().Where(o => o.Name.Trim() == valuestr);
                        }, item);
                        if (model != null)
                        {
                            item.Value = model.Id;
                            return;
                        }
                    }

                    if (attr.Reference == typeof(Domain.CarBrand))
                    {
                        Domain.CarBrand model = GetModel<Domain.CarBrand>(() =>
                        {
                            return PersistentContext.Set<Domain.CarBrand>().Where(o => o.Name.Trim() == valuestr);
                        }, item);
                        if (model != null)
                        {
                            item.Value = model.Id;
                            return;
                        }
                    }
                    
                    throw new Exception("第" + item.Row + "行," + item.Name + "错误：找不到对应数据");
                }
            }
        }

        private E GetModel<E>(Func<IQueryable<E>> query, ImportItem item)
            where E : class
        {
            if (query == null)
            {
                return null;
            }
            IQueryable<E> result = query();
            if (result.Count() >= 2)
            {
                throw new Exception("第" + item.Row + "行," + item.Name + "错误：此数据不唯一，请在后边注明ID再提交");
            }
            if (result.Count() == 1)
            {
                return  result.FirstOrDefault();
            }
            return null;
        }

        
    }
}
